package com.fhminyi.GUI;

import com.fhminyi.dao.OrderDao;
import com.fhminyi.dao.OrderItemDao;
import com.fhminyi.dao.ProductDao;
import com.fhminyi.model.Order;
import com.fhminyi.model.OrderItem;
import com.fhminyi.model.Product;
import com.fhminyi.model.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.SQLException;
import java.util.List;

public class OrderListFrame extends JFrame {
    private User currentUser;
    private OrderDao orderDao = new OrderDao();
    private OrderItemDao orderItemDao = new OrderItemDao(); // 添加 OrderItemDao 成员变量
    private ProductDao productDao = new ProductDao(); // 添加 ProductDao 成员变量
    private JTable orderTable;

    public OrderListFrame(User currentUser) {
        this.currentUser = currentUser;
        setTitle("我的订单");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        // 创建表格模型并设置列名
        DefaultTableModel tableModel = new DefaultTableModel();
        tableModel.addColumn("订单号");
        tableModel.addColumn("商品名称");
        tableModel.addColumn("商品数量");
        tableModel.addColumn("商品单价");
        tableModel.addColumn("订单总价");
        tableModel.addColumn("订单状态");
        tableModel.addColumn("订单日期");

        orderTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(orderTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        loadOrders();

        add(panel);
    }

    private void loadOrders() {
        try {
            List<Order> orders = orderDao.getOrdersByUserId(currentUser.getUserId());
            DefaultTableModel tableModel = (DefaultTableModel) orderTable.getModel();
            tableModel.setRowCount(0); // 清空表格

            for (Order order : orders) {
                List<OrderItem> orderItems = orderItemDao.getOrderItemsByOrderId(order.getOrderId()); // 通过订单ID获取订单商品列表
                for (OrderItem orderItem : orderItems) {
                    Product product = productDao.getProductById(orderItem.getProductId()); // 通过商品ID获取商品信息
                    tableModel.addRow(new Object[]{
                        order.getOrderId(),
                        product.getProductName(),
                        orderItem.getQuantity(),
                        orderItem.getPrice(),
                        order.getTotalPrice(),
                        order.getStatus(),
                        order.getOrderDate()
                    });
                }
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "获取订单列表失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) {
        new OrderListFrame(new User()).setVisible(true);
    }
}